log("cnl-search.js loaded");
/*
 * Copyright (c) 2009 Bui Viet Thanh (thanhbv@gmail.com).
 *
 * This file is part of clicknlearn.
 *
 * clicknlearn is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * clicknlearn is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with clicknlearn.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {
    const ROOT_PADDING = {top: 70, left: 0, right: 0, bottom: 0};
    const BORDER = 3;

    var cnlDiv$ = null, select$;
    function prepareCnlDiv$(){
        cnlDiv$ = $(CNL.data.CNL_HTML);
        select$ = cnlDiv$.find("#clicknlearn_source_select");
        $.each(CNL.data.sources, function(i, v) {
            select$.append($("<option></option>").
//                    attr("value", i).
                    text(v.name));
        });
        select$ = select$.combobox({arrowURL: CNL.data.arrowURL,
            arrowClickedURL: CNL.data.arrowURL,
            width: 20, autoShow: false});
        cnlDiv$.find('#clicknlearn_form input[value="Search"]').click(
            function(e){
                CnlSearch.doQuery()
            });
        cnlDiv$.find('#clicknlearn_query,#clicknlearn_source_select').keydown(
            function(e) {
                if(e.which == 13)//Enter keycode
                    CnlSearch.doQuery();
                if(! e.altKey)
                    return true;
                if(e.which == 18){//only alt key is down
                    var isListShown = select$.combobox('isListVisible');
                    log(["down: isListShown", isListShown]);
                    if(! isListShown)
                        select$.combobox('showList', e);
                }else{
                    var code = e.which - 48;//press '1' => code = 1
                    if(code < 1 || code > CNL.data.sources.length || code > 9)
                        return true;
                    CnlSearch.doQuery(null, code-1);
                }
                return false;
            }).keyup(
            function(e){
                log(["up: e.altKey", e.altKey]);
                if(e.which == 18 || e.altKey){
                    var isListShown = select$.combobox('isListVisible');
                    log(["up: isListShown", isListShown]);
                    if(isListShown)
                        select$.combobox('hideList');
                    return false;
                }
            });
    }
    function showPopup(x, y, windowX, windowY, query){
        var frame = null, form, moveHandle, resizeHandle;
        if(cnlDiv$ == null){
            prepareCnlDiv$();
            frame =  cnlDiv$.find('#clicknlearn_frame').get(0);
            form = cnlDiv$.find('#clicknlearn_form').get(0);
            moveHandle = cnlDiv$.find('#clicknlearn_move').get(0);
            resizeHandle = cnlDiv$.find('#clicknlearn_resize').get(0);
            Resizer.makeMovableAndResizable(frame, moveHandle, resizeHandle, form);
        }
        if(frame == null){
            frame =  cnlDiv$.find('#clicknlearn_frame').get(0);
            form = cnlDiv$.find('#clicknlearn_form').get(0);
            moveHandle = cnlDiv$.find('#clicknlearn_move').get(0);
            resizeHandle = cnlDiv$.find('#clicknlearn_resize').get(0);
        }
        var full_frame_height = 2 * BORDER + ROOT_PADDING.top + parseInt(frame.style.height) + ROOT_PADDING.bottom,
            full_frame_width = 2 * BORDER + ROOT_PADDING.left + parseInt(frame.style.width) + ROOT_PADDING.right;
        var left = x, top = y;
        if (windowX + full_frame_width >= window.innerWidth) {
            left = x - full_frame_width;
            if (left < 0) left = 5;
        }
        if (windowY + full_frame_height >= window.innerHeight) {
            top = y - full_frame_height;
            if (top < 0) top = 5;
        }
        frame.style.top = form.style.top = moveHandle.style.top = top + 'px';
        frame.style.left = form.style.left = moveHandle.style.left = left + 'px';
        resizeHandle.style.top = (top + full_frame_height - 16) + 'px';
        resizeHandle.style.left = (left + full_frame_width - 16) + 'px';
        if(document.getElementById('clicknlearn') == null)
            cnlDiv$.appendTo('body');
        if(query)
            CnlSearch.doQuery(query);
        cnlDiv$.fadeIn('slow');
    }
    //~~~~~~public methods~~~~~~//
    var CnlSearch = function(){};
    /** cnl is: {word, sentence, isNewWord} with      :
     *  word - the word that user click on
     *  sentence - the remind sentence if this word has been add to CNL_DB
     *      - (else) the sentence that user click on
     *  isNewWord - false only if this word is in CNL_DB && the status of it in DB is not 'knewByHeart'
     * or null if not found
     * @param e - (FF) mouseEvent with
     * e.rangeParent The DOM node that user click on
     * e.rangeOffset Pos in the parent node that user click on
     */
    CnlSearch.search = function(e) {
        var word = CnlSelection.getClickedSelectionText(e);
        if (!word)
            word = CnlSelection.getClickedWord(e);
        log(["Search", word]);
        showPopup(e.pageX, e.pageY, e.clientX, e.clientY, word);
        if (!word)
            return;
        function getRemindDataCb(remindData){
            var sentence = remindData && remindData.remind?
                        remindData.remind : CnlSelection.getClickedSentence(e, false);
            cnlDiv$.find("#clicknlearn_remind").val(sentence);
//            var cnl = {word: word, sentence: sentence, isNewWord: remindData != null && remindData.read == 0};
//            TODO: impl getRemindDataCb" + CNL.data.source_url + cnl.word
        }
        CNL.sendMessage({method: "getRemindData", arg: word}, getRemindDataCb);
    };
    CnlSearch.hide = function(){
        cnlDiv$.fadeOut('slow');
    };
    /**Checks whether a click event was inside the current popup frame.*/
    CnlSearch.isClickInsideFrame = function(e) {
        var elem = e.target;
        while (elem != null) {
            if(elem.id == 'clicknlearn')
                return true;
            elem = elem.parentNode;
        }
        return false;
    };
    CnlSearch.doQuery = function(query, srcIdx, remind){
        var query$ = cnlDiv$.find("#clicknlearn_query");
        if(query)
            query$.val(query);
        else{
            query = query$.val();
            if(query == null || query == '')
                return;
        }
        query$.focus();
        query$.select();
        if(srcIdx)
            select$.combobox('finishSelection', srcIdx);//changeSelection
        else
            srcIdx = select$.combobox('findSelection');// cnlDiv$.find('#clicknlearn_source_select').val();
        CNL.data.srcIdx = srcIdx;
//        CNL.data.srcIdx = srcIdx || cnlDiv$.find('#clicknlearn_source_select option:selected').get(0).value;
        var src = CNL.data.sources[srcIdx];
        var url = encodeURI(src.url.replace(/\*/g, query));
        cnlDiv$.find('#clicknlearn_frame').attr('src', url);
    };
    window.CnlSearch = CnlSearch;
})();